<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>分类管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="4">
          <el-button type="primary" @click="showAddDialog">添加分类</el-button>
        </el-col>
      </el-row>

      <table-tree
        :data="cateList"
        :columns="cateListColumns"
        :selection-type="false"
        :show-index="true"
        :expand-type="false"
      >
        <template slot="deleted" slot-scope="scope">
          <i
            class="el-icon-circle-check"
            style="color:rgb(68,178,170)"
            v-if="scope.row.cat_deleted===false"
          ></i>
          <i class="el-icon-circle-close" v-else></i>
        </template>
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level==0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level==1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row.cat_id)"
          >修改</el-button>
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="delCate(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </table-tree>

      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>

      <el-dialog title="添加分类" :visible.sync="addDialogVisible" width="50%" @close="addDialogClosed">
        <el-form ref="addFormRef" :model="addForm" label-width="80px" :rules="addFormRules">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="分类上级" prop="cat_pid">
            <el-cascader
              expand-trigger="hover"
              :options="patInfo"
              @change="patChange"
              :props="patProps"
              :change-on-select="true"
              v-model="selectedPat"
              :clearable="true"
              style="width:100%"
            ></el-cascader>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCate">确 定</el-button>
        </span>
      </el-dialog>

      <el-dialog
        title="修改分类"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editDialogClosed"
      >
        <el-form ref="editFormRef" :model="editForm" label-width="80px" :rules="editFormRules">
          <el-form-item label="分类名称" prop="cateName">
            <el-input v-model="editForm.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCate">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateList: [],

      /** 分页功能1 */
      queryInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 5
      },
      total: 0,
      /** 分页功能2 */

      /** 添加分类1 */
      addDialogVisible: false,
      addForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0
      },
      addFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      /** 添加分类2 */

      /** 修改分类1 */
      editDialogVisible: false,
      editForm: {
        cat_name: ''
      },
      editFormRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      /** 修改分类2 */

      /** 表格树相关1 */
      cateListColumns: [
        { label: '分类名称', prop: 'cat_name', width: '200px' },
        {
          label: '是否有效',
          prop: 'cat_deleted',
          width: '200px',
          type: 'template',
          template: 'deleted'
        },
        {
          label: '排序',
          prop: 'cat_level',
          width: '200px',
          type: 'template',
          template: 'level'
        },
        { label: '操作', width: '200px', type: 'template', template: 'opt' }
      ],
      /** 表格树相关2 */

      /** 添加分类-父级级联1 */
      patInfo: [],
      selectedPat: [],
      patProps: {
        label: 'cat_name',
        value: 'cat_id',
        // 设置了该children属性，鼠标滑过第一级别信息就可以把其直接填充到表单域里边
        children: 'children'
      }
      /** 添加分类-父级级联2 */
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    /** 添加分类-父级级联1 */
    patChange() {
      if (this.selectedPat.length === 0) {
        this.addForm.cat_pid = 0
        this.addForm.cat_level = 0
      } else {
        var len = this.selectedPat.length
        this.addForm.cat_pid = this.selectedPat[len - 1]
        this.addForm.cat_level = len
      }
      // console.log(this.selectedPat, '---------', this.addForm.cat_pid)
    },
    /** 添加分类-父级级联2 */
    /** 添加分类1 */
    async showAddDialog() {
      this.addDialogVisible = true
      // 获取可供选取的父级分类信息
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 }
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取上级分类数据失败！')
      }
      this.patInfo = res.data
    },
    addDialogClosed() {
      this.addDialogVisible = false
      this.$refs.addFormRef.resetFields()

      this.addForm.cat_pid = 0
      this.selectedPat = []
    },
    addCate() {
      this.$refs.addFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.post(
            'categories',
            this.addForm
          )

          if (res.meta.status !== 201) {
            return this.$message.error(res.meta.msg)
          }

          this.getCateList()
          this.addDialogClosed()
          this.$message.success(res.meta.msg)
        }
      })
    },
    /** 添加分类2 */

    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表数据失败！')
      }
      console.log(res)
      this.total = res.data.total
      this.cateList = res.data.result
    },

    /** 分页功能1 */
    handleSizeChange(val) {
      this.queryInfo.pagesize = val
      this.getCateList()
    },
    handleCurrentChange(val) {
      this.queryInfo.pagenum = val
      this.getCateList()
    },
    /** 分页功能2 */

    /** 修改分类1 */
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$http.get(`categories/${id}`)
      if (res.meta.status !== 200) {
        this.$message.error('获取修改分类失败')
      }

      this.editForm = res.data
    },
    editDialogClosed() {
      this.editDialogVisible = false
      this.$refs.editFormRef.resetFields()
    },
    editCate() {
      this.$refs.editFormRef.validate(async valid => {
        if (valid) {
          const { data: res } = await this.$http.put(
            `categories/` + this.editForm.cat_id,
            this.editForm
          )

          if (res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }

          this.getCateList()
          this.editDialogClosed()
          this.$message.success(res.meta.msg)
        }
      })
    },
    /** 修改分类2 */

    async delCate(id) {
      const cfm = await this.$confirm(
        '此操作将永久删除该分类, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)

      if (cfm === 'confirm') {
        const { data: res } = await this.$http.delete(`categories/${id}`)

        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }

        this.getCateList()
        this.$message.success(res.meta.msg)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.box-card {
  margin-top: 15px;
  box-shadow: 0 1px 1px rgb(199, 202, 205);
}
.el-table {
  margin-top: 15px;
  font-size: 12px;
}
.el-pagination {
  margin-top: 15px;
}
.el-tag {
  margin: 10px 5px;
}
.zk-table {
  margin-top: 15px;
}
</style>
